package com.surelution.projects.crm

import java.text.SimpleDateFormat

class CardConsumeRawController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }
	def springSecurityService
	def ImportExcelService
	def htmlTableParserService
	
	def importCardConsumeRaw = {
		def fromLine =1
		def file = params.cardConsumeRawFile
		int lineNum = 0
		def fileName = file.originalFilename
		ImportExcel excel = ImportExcelService.storeFile(file.inputStream,fileName)
		
		BufferedReader br = new BufferedReader(new InputStreamReader(file.inputStream, "utf8"))
		def rows = htmlTableParserService.parse(br)

		//TODO should save cardConsumeRaw, cardConsume seperately
		//It should save CardConsumeRaw first, and with (flush:false), flush at the last record
		//the enter the 2nd loop, save CardConsume each attached cardConsumeRaw
		//because CardConsumeRaw is null when the input is duplicated, so the code fails at CardConsume saving
		rows.each {row->
			if(lineNum > fromLine) {
				println row
				CardConsumeRaw cardConsumeRaw = new CardConsumeRaw("tradeAt":row[0],"tradeType":row[1],"amount":row[2],"discount":row[3],"preTrandeBalance":row[4],"goodsType":row[5],
					"volume":row[6],"cardNo":row[7],"holderName":row[8],"accountAcceptBranch":row[9],"tradeTime":row[10],,"vehicleNo":row[11],"businessDate":row[12],"tradeDate":row[13],"grayTrade":row[14])
				cardConsumeRaw.processed = false
				cardConsumeRaw.save(flush:true)
				
				if(cardConsumeRaw.attached) {
					def memberCard = MemberCard.findByCardNo(row[7], [cache:true])
					GasTypeRaw gasType = GasTypeRaw.findByTypeName(cardConsumeRaw.goodsType, [cache:true])
					if(memberCard&&gasType) {
						CardConsume cardConsume = new CardConsume(member:memberCard,rawInfo:cardConsumeRaw,
							tradeAt: row[0], gasType: gasType.type)
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
						Date tradeTime = sdf.parse(row[10])
						cardConsume.amount = Float.parseFloat(row[6])
						cardConsume.tradeTime = tradeTime
						cardConsume.save(flush:true)
					}
					println cardConsumeRaw
				}
			}
			lineNum++
		}
		excel.uploader = springSecurityService.principal.username
		excel.type = "加油卡消费明细列表"
		excel.save(flush:true)
		flash.message = "${message(code: 'default.updateFileSuccess.message', args: [message(code: 'cardConsumeRaw.label', default: 'cardConsumeRaw')])}"
		redirect(action:"list")
	}

	def search = {
		def cardNo = MemberCard.get(params.id).cardNo
		def sdf = new SimpleDateFormat('yyyy-MM-dd')
		def dateFrom = params.dateFrom? sdf.parse(params.dateFrom):null
		def dateTo = params.dateTo? sdf.parse(params.dateTo):null
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def cardConsumeRawInstance = CardConsume.createCriteria().list([max:params.max, offset:params.offset]) {
			if(cardNo){
				createAlias("rawInfo", "r")
				eq('r.cardNo', cardNo)
			}
			if(dateFrom) {
				ge("tradeTime", dateFrom)
			}
			if(dateTo) {
				le("tradeTime", dateTo)
			}
			order("tradeTime", "desc")
		}
		[cardConsumeRawInstance: cardConsumeRawInstance, consumeListTotal:cardConsumeRawInstance.totalCount, cardNo:cardNo]
	}

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
		def dateFrom = params.dateFrom? (params.dateFrom + " 00:00:00"):null
		def dateTo = params.dateTo? (params.dateTo + " 00:00:00"):null
		def result = CardConsumeRaw.createCriteria().list ([max:params.max, offset:params.offset]){
			if(dateFrom) {
				ge("tradeDate", dateFrom)
			}
			if(dateTo) {
				le("tradeDate", dateTo)
			}
			order("tradeDate","desc")
		}
        [cardConsumeRawInstanceList: result, cardConsumeRawInstanceTotal: result.totalCount]
    }

    def create = {
        def cardConsumeRawInstance = new CardConsumeRaw()
        cardConsumeRawInstance.properties = params
        return [cardConsumeRawInstance: cardConsumeRawInstance]
    }

    def save = {
        def cardConsumeRawInstance = new CardConsumeRaw(params)
        if (cardConsumeRawInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), cardConsumeRawInstance.id])}"
            redirect(action: "show", id: cardConsumeRawInstance.id)
        }
        else {
            render(view: "create", model: [cardConsumeRawInstance: cardConsumeRawInstance])
        }
    }

    def show = {
        def cardConsumeRawInstance = CardConsumeRaw.get(params.id)
        if (!cardConsumeRawInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), params.id])}"
            redirect(action: "list")
        }
        else {
            [cardConsumeRawInstance: cardConsumeRawInstance]
        }
    }

    def edit = {
        def cardConsumeRawInstance = CardConsumeRaw.get(params.id)
        if (!cardConsumeRawInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [cardConsumeRawInstance: cardConsumeRawInstance]
        }
    }

    def update = {
        def cardConsumeRawInstance = CardConsumeRaw.get(params.id)
        if (cardConsumeRawInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (cardConsumeRawInstance.version > version) {
                    
                    cardConsumeRawInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw')] as Object[], "Another user has updated this CardConsumeRaw while you were editing")
                    render(view: "edit", model: [cardConsumeRawInstance: cardConsumeRawInstance])
                    return
                }
            }
            cardConsumeRawInstance.properties = params
            if (!cardConsumeRawInstance.hasErrors() && cardConsumeRawInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), cardConsumeRawInstance.id])}"
                redirect(action: "show", id: cardConsumeRawInstance.id)
            }
            else {
                render(view: "edit", model: [cardConsumeRawInstance: cardConsumeRawInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def cardConsumeRawInstance = CardConsumeRaw.get(params.id)
        if (cardConsumeRawInstance) {
            try {
                cardConsumeRawInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'cardConsumeRaw.label', default: 'CardConsumeRaw'), params.id])}"
            redirect(action: "list")
        }
    }
}
